﻿using Microsoft.Extensions.DependencyInjection;
using ZeroSum.DependencyInjection.Attributes;
using ZeroSum.Extend.Mapper.Extensions;
using ZeroSum.Models;
using ZeroSumZSA.Application.ApplicationServices.Users.Dto.In;
using ZeroSumZSA.Application.ApplicationServices.Users.Dto.Out;
using ZeroSumZSA.Application.ApplicationServices.Users.Dto.Query;
using ZeroSumZSA.Core.Aggregates.UserAggregate;
using ZeroSumZSA.Core.DomainServices.Users;

namespace ZeroSumZSA.Application.ApplicationServices.Users;

[Register(ServiceLifetime.Scoped)]
public class UserApplicationService : IUserApplicationService
{
    private readonly IUserDomainService _domainService;

    public UserApplicationService(IUserDomainService domainService)
    {
        _domainService = domainService;
    }

    public async Task<PagedResponseModel<PageUserDto>> Page(PageUserQuery query)
    {
        var users = await _domainService.Query(query.Keyword, query.PageNumber, query.PageSize);
        // var users = users.ToPagedList<User, PageUserDto>(query.PageNumber, query.PageSize);
        var list = users.MapTo<List<PageUserDto>>();
        var count = await _domainService.Count(query.Keyword);
        return new PagedResponseModel<PageUserDto>(query.PageNumber, query.PageSize, count, list);
    }

    public async Task AddAsync(AddUserDto dto)
    {
        var entity = dto.MapTo<User>();
        await _domainService.AddAsync(entity);
    }

    public async Task DeleteAsync(DeleteUserDto dto)
    {
        await _domainService.DeleteAsync(dto.Id);
    }

    public async Task UpdateAsync(EditUserInput dto)
    {
        await _domainService.CheckUserUpdate(dto.Name, dto.Id);
        var role = await _domainService.GetByIdAsync(dto.Id);
        var entity = dto.MapTo(role);
        await _domainService.UpdateAsync(entity);
    }

    public async Task<DetailUserDto> Detail(DetailUserQuery query)
    {
        var role = await _domainService.GetByIdAsync(query.Id);
        return role.MapTo<DetailUserDto>();
    }
}